/**
 * Created by jackliu on 15/12/16.
 */

var common = require('../../common');
var pool = require('../index');
var mysql = require('mysql');
var ItbBaseModel = require('./ItbBaseModel');


// Schema 结构
var ItbProductVer = function(obj){
    ItbBaseModel.call(this,obj);

  // 以下为表定义数据，需要的字段就填入
  //  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '项目id',
  //`device` int(8) NOT NULL DEFAULT '0' COMMENT '平台: 1 标识一键生成iOS端, 2 标识一键生成android端',
  //`ver` varchar(20) NOT NULL DEFAULT '' COMMENT '版本号: 例如5.6.0',
  //`url` text COMMENT '下载地址',
  //`release` int(2) NOT NULL DEFAULT '10' COMMENT '10:测试版, 20:release版',
  //`chk_freq` bigint(10) NOT NULL DEFAULT '0' COMMENT 'check频率: 单位小时(h)',
  //`valid` int(1) NOT NULL DEFAULT '0' COMMENT '0: 无效, 1:有效',
  //`desc` text COMMENT '备注描述',
  //`create_time` datetime NOT NULL,
  //`update_time` datetime NOT NULL,
  //`update_by` varchar(50) NOT NULL DEFAULT '',
  //`del_flg` int(1) NOT NULL DEFAULT '0' COMMENT '删除flg',
};
ItbProductVer.prototype = new ItbBaseModel();

// 取得表名
ItbProductVer.prototype.getTableName = function(){
    return 'itb_product_ver';
}
// 取得查询语句中where 后面匹配主键的条件（需要各派生类进行重载）
ItbProductVer.prototype.getWhereConditionOfKeyEqual = function(){
    return 'id='+this.id;
}

//------------------------------------------------------------------
ItbProductVer.prototype.getLastAppVersion = function(device, callback){
    var THIS = this;
    var tableName = this.getTableName();

    pool.pool.getConnection(function(err, connection) {
        // Use the connection
        if(err) {
            return callback(err);
        }

        var sql =
            " SELECT * " +
            " FROM itb_product_ver p " +
            " WHERE p.device=" +device+
            "   AND p.release=20 " +
            "   AND p.valid=1 " +
            "   AND p.del_flg=0 " +
            " ORDER BY p.update_time DESC LIMIT 1 " ;

        console.log(sql);
        connection.query(sql, function(error, result) {
            // And done with the connection.
            connection.release();

            if(error) {
                return callback(error);
            }

            if(result && result.length > 0) {
                return callback(null, result[0]);
            } else {
                return callback(null, null);
            }


        });
    });
};

// 导出
module.exports = ItbProductVer;